﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web.Script.Serialization;

namespace Twi.COMMON.Core
{
    /*
     * CopyRight:©2012 Twilight软件开发工作室版权所有
     * Author:xuzhihong
     * Create Date: 2012-07-24
     * Description: 
     */
    public class TwiJsonHelper
    {
        /// <summary>
        /// 将DataTable转化为Json字符串
        /// </summary>
        /// <param name="dt"></param>
        /// <remarks>即以前的ConventDataTableToJson.Serialize方法</remarks>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt, bool needAppendInfo = true, string totalCountField = "totalCount", string dataField = "data")
        {
            return TwiDataTableHelper.ToJson(dt, needAppendInfo, totalCountField, dataField);
        }


        /// <summary>
        /// 把DataTable转换为TwiReturn序列化后的字符串
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="twi"></param>
        /// <returns></returns>
        public static string DataTableToTwiJson(DataTable dt,ref TwiReturn twi)
        {
            return TwiDataTableHelper.ToTwiJson(dt, ref twi);
        }

        /// <summary>
        /// 把DataTable转换为TwiReturn
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="twi"></param>
        /// <returns></returns>
        [Obsolete("请使用TwiDataTableHelper.ToTwiReturn方法代替.2015-04-30")]
        public static void DataTableToTwiReturn(DataTable dt, ref TwiReturn twi)
        {
            TwiDataTableHelper.ToTwiReturn(dt, ref twi);
        }


        /// <summary>
        /// List<T>转换为JSON字符串
        /// </summary>
        /// <returns></returns>
        public static string ListToJson<T>(IList<T> list, int count=0,bool needAppendInfo = true, string totalCountField = "totalCount", string dataField = "data")
        {
            if (count == 0)
            {
                count = list.Count;
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strJson = serializer.Serialize(list);
            if (needAppendInfo)
            {
                strJson = strJson.Substring(1);
                strJson = strJson.Insert(0, "{\""+totalCountField+"\":" + count + ",\""+dataField+"\":[");
                strJson += "}";
            }
            return strJson;
        }


        /// <summary>
        /// 将Json格式字符串转换为字典Dictionary<string, string)
        /// </summary>
        /// <param name="json"></param>
        /// <remarks>如果含有冒号（：）会影响到结果</remarks>
        /// <returns></returns>
        public static Dictionary<string, string> JsonToDictionary(string json)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(json))
            {
                dict = json.Trim(new char[] { '{', '}' }).Split(',').ToDictionary(s => s.Split(':')[0].Trim('"'), s => (string)s.Split(':')[1].Trim('"'));
            }
            return dict;
        }

        public static Dictionary<string, object> JsonToDictionary2(string json)
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            if (!string.IsNullOrEmpty(json))
            {
                dict = json.Trim(new char[] { '{', '}' }).Split(',').ToDictionary(s => s.Split(':')[0].Trim('"'), s => (object)s.Split(':')[1].Trim('"'));
            }
            return dict;
        }

        /// <summary>
        /// 根据映射修改表列名
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="mapping"></param>
        /// <returns></returns>
        public static DataTable ChangeColumnName(DataTable dt, DataBaseFieldMapping mapping)
        {
            foreach (DataColumn column in dt.Columns)
            {
                string key = column.ColumnName.ToUpper();
                if (mapping.DictFieldMapping.ContainsKey(key))
                {
                    column.ColumnName = mapping.DictFieldMapping[key];
                }
            }
            return dt;
        }

        /// <summary>
        /// 转化DataTable列名为大写
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static DataTable ColNameToUpper(DataTable dt)
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                dt.Columns[i].ColumnName = dt.Columns[i].ColumnName.ToUpper();
            }
            return dt;
        }
    }


    /// <summary>
    /// 数据库字段映射
    /// </summary>
    public class DataBaseFieldMapping
    {
        public DataBaseFieldMapping()
        {
            DictFieldMapping = new Dictionary<string, string>();
        }

        public DataBaseFieldMapping(Dictionary<string, string> dictFieldMapping)
        {
            DictFieldMapping = dictFieldMapping;
        }

        /// <summary>
        /// 字段映射字典
        /// </summary>
        public Dictionary<string, string> DictFieldMapping
        {
            get;
            set;
        }

    }
}
